﻿CREATE FUNCTION [dbo].[Split]
(
	 @ids VARCHAR(max) -- List of delimited items
  , @delimiter VARCHAR(10) = ',' -- delimiter that separates items
) RETURNS @List TABLE (Id INT)

AS
BEGIN
DECLARE @sItem INT
WHILE CHARINDEX(@delimiter,@ids,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@ids,1,CHARINDEX(@delimiter,@ids,0)-1))),
  @ids=RTRIM(LTRIM(SUBSTRING(@ids,CHARINDEX(@delimiter,@ids,0)+LEN(@delimiter),LEN(@ids))))
 
 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@ids) > 0
 INSERT INTO @List SELECT @ids -- Put the last item in
RETURN
END
GO